
package org.finegold.core.netty.core.session;



import org.finegold.core.netty.core.model.ResultCode;
import org.finegold.core.netty.core.model.ServerResponse;
import org.finegold.core.tool.utils.ProtostuffUtil;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: 会话管理者
 *
 * @author QinYueFeng
 * @since: 1.0
 * Create Date Time: 2018/7/4 16:38
 * Update Date Time:
 * @see
 */
public class SessionManager {

    /**
     * 在线会话
     */
    private static final ConcurrentHashMap<String, Session> onlineSessions = new ConcurrentHashMap<>();

    /**
     * 加入
     * @param userId
     * @param session
     * @return
     */
    public static boolean putSession(String userId, Session session){
        if(!onlineSessions.containsKey(userId)){
            boolean success = onlineSessions.putIfAbsent(userId, session)== null? true : false;
            return success;
        }
        return false;
    }

    /**
     * 移除
     * @param mobile
     */
    public static Session removeSession(String mobile){
        return onlineSessions.remove(mobile);
    }

    /**
     * 发送消息[protoBuf协议]
     * @param <T>
     * @param mobile
     * @param message
     */
    public static <T> void sendMessage(String mobile, short module, short cmd, T message){
        Session session = onlineSessions.get(mobile);
        if (session != null && session.isConnected()) {
            ServerResponse response = new ServerResponse(module, cmd, ResultCode.SUCCESS);
            if (message != null) {
                response.setData(ProtostuffUtil.serialize(message));
            }
            session.write(response);
        }
    }

	/**
	 * 发送消息文本
	 * @param <T>
	 * @param mobile
	 * @param message
	 */
	public static <T> void sendPlainMessage(String mobile, T message){
		Session session = onlineSessions.get(mobile);
		if (session != null && session.isConnected()) {
			session.write(message);
		}
	}

    /**
     * 是否在线
     * @param mobile
     * @return
     */
    public static boolean isOnline(String mobile){
        return onlineSessions.containsKey(mobile);
    }

    /**
     * 获取在线
     * @return
     */
    public static Set<String> getOnline() {
        return Collections.unmodifiableSet(onlineSessions.keySet());
    }

    /**
     * 移除会话,关闭连接
     * @param mobile
     */
    public static void removeSessionCloseSocket(String mobile) {
        Session oldSession = SessionManager.removeSession(mobile);
        oldSession.removeAttachment();
        oldSession.close();
    }
}
